const app = getApp()
const maxLen = 10

Page({
  data: {
    name:[],
    selected: [],
    selectedIndex: -1
  },

  onLoad: function(e) {
    wx.getStorage({
      key: 'nameArray',
      success: res => {
        this.setData({
          name: res.data
        })
      },
      fail: err => {
        var tempArray = []
        let len = app.globalData.name.length
        for(let i = 0; i < len; i++) {
          tempArray[i] = app.globalData.name[i]
        }

        this.setData({
          name: tempArray
        })
      }
    })

    wx.getStorage({
      key: 'selectedIndex',
      success: res => {
        this.setData({
          selectedIndex: res.data
        })
      }
    })
  },

  onUnload: function(e) {
    console.log('onUnload')
  },
  
  add: function(e) {
    if(this.data.name.length >= maxLen) {
      this.show('添加失败，方案数量超过上限')
      return
    }

    let tempName = this.data.name
    let newIndex = 1
    for(newIndex = 1; newIndex < maxLen+100; newIndex++) {
      let tempFlag = true
      for(let i = 0; i < tempName.length; i++) {
        if(('自定义方案'+newIndex) == tempName[i]) {
          tempFlag = false
        }
      }

      if(tempFlag) break
    }
    tempName.push('自定义方案' + newIndex)
    this.setData({
      name: tempName
    })

    wx.setStorage({
      data: this.data.name,
      key: 'nameArray',
    })

    wx.showToast({
      title: '增加成功',
    })
  },

  remove: function(e) {
    if(this.data.name.length <= 1) {
      this.show('删除失败，请保留至少一个方案')
      return
    }

    let tempName = this.data.name
    let selectedIndex = 0
    for(selectedIndex = this.data.selected.length-1; selectedIndex >= 0; selectedIndex--) {
      if(this.data.selected[selectedIndex]) break;
    }
    if(selectedIndex == -1) {
      this.show('请先选择一个方案')
      return
    }
    if(this.data.selectedIndex == selectedIndex) {
      this.show('当前方案已启用，无法删除')
      return
    }

    wx.removeStorage({
      key: 'plan' + tempName[selectedIndex],
    })

    let delta = (selectedIndex > this.data.selectedIndex) ? 0 : -1
    tempName.splice(selectedIndex, 1)
    this.setData({
      name: tempName,
      selected: [],
      selectedIndex: this.data.selectedIndex + delta
    })

    wx.setStorage({
      data: this.data.name,
      key: 'nameArray',
    })

    wx.showToast({
      title: '删除成功',
    })
  },

  select: function(e) {
    let index = e.currentTarget.dataset.id
    let flag = !this.data.selected[index]
    this.setData({
      selected: [] 
    })
    this.setData({
      ['selected[' + index + ']']: flag
    })
  },

  show: function(str) {
    wx.showToast({
      title: str,
      icon: 'none'
    })
  }
})